package com.swz.dcrm.ui.car;


import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.graphics.Color;
import android.os.Bundle;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bumptech.glide.Glide;
import com.swz.dcrm.adpter.CarColorAdapter;
import com.swz.dcrm.adpter.CarParamAdapter;
import com.swz.dcrm.adpter.GlobalAdapter;
import com.swz.dcrm.adpter.MultiItemTypeAdapter;
import com.swz.dcrm.model.BaseResponse;
import com.swz.dcrm.model.CarBrand;
import com.swz.dcrm.model.CarModel;

import com.swz.dcrm.model.CarParam;
import com.swz.dcrm.model.CarSeries;
import com.swz.dcrm.ui.base.BaseFragment;
import com.swz.dcrm.R;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.navigation.fragment.NavHostFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import com.swz.dcrm.R;
import com.swz.dcrm.ui.viewmodel.CarBrandViewModel;
import com.swz.dcrm.ui.viewmodel.CarManagementViewModel;
import com.swz.dcrm.util.CustomDecoration;
import com.swz.dcrm.util.FileUtils;
import com.swz.dcrm.util.HorizontalDecoration;
import com.swz.dcrm.util.RxTimer;
import com.swz.dcrm.util.Tool;
import com.xh.baselibrary.callback.OnClickListener;
import com.xh.baselibrary.widget.BounceScrollView;
import com.xh.baselibrary.widget.ClickImageView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.inject.Inject;

/**
 * A simple {@link Fragment} subclass.
 */
public class CarDetailFragment extends BaseFragment {

    @BindView(R.id.toolbar_title)
    TextView title;
    @BindView(R.id.iv_logo)
    ImageView ivLogo;
    @BindView(R.id.scroll)
    BounceScrollView scrollView;
    private int ivHeight;
    @BindView(R.id.toolbar)
    ConstraintLayout toolbar;
    @BindView(R.id.iv_back)
    ClickImageView ivBack;
    @BindView(R.id.tv_car_model)
    TextView tvCarModel;
    @BindView(R.id.tv_price1)
    TextView price1;
    @BindView(R.id.tv_price2)
    TextView price2;
    @BindView(R.id.tv_engine)
    TextView tvEngine;
    @BindView(R.id.tv_gas)
    TextView tvGas;
    @BindView(R.id.tv_color)
    TextView tvColor;
    @BindView(R.id.rv_param)
    RecyclerView rvParam;

    @BindView(R.id.scroll1)
    BounceScrollView scrollView1;
    @BindView(R.id.iv_back1)
    ClickImageView ivBack1;
    @BindView(R.id.c)
    ConstraintLayout c;
    @BindView(R.id.rv_color)
    RecyclerView rvColor;
    @BindView(R.id.iv_collect)
    ImageView ivCollect;
    List<CarParam> needRemove = new ArrayList<>();

    private CarParamAdapter carParamAdapter;
    private CarColorAdapter carColorAdapter;
    CarBrand carBrand = new CarBrand();
    CarSeries carSeries = new CarSeries();
    CarModel carModel;
    @Inject
    CarBrandViewModel carBrandViewModel;
    @Inject
    CarManagementViewModel carManagementViewModel;

    private Disposable mDisposable;
    RxTimer rxTimer;

    public static CarDetailFragment newInstance() {

        return new CarDetailFragment();
        // Required empty public constructor
    }



    @Override
    public void onLoadRetry() {
        if (!isNetworkConnected(getContext())) {
            mHolder.showLoadingStatus(GlobalAdapter.NET_ERROR);
            return;
        }

        carManagementViewModel.getCarDetail(carModel.getId())
                .observe(this, carDetailBaseResponse -> {

                    if (carDetailBaseResponse.isSuccess() && carDetailBaseResponse.getData().getId() == carModel.getId()) {

                        mDisposable = Observable.create((ObservableOnSubscribe<CarParam>) e -> {
                            for (CarParam carParam : carDetailBaseResponse.getData().getCarEnList()) {
                                if (carParam.getCnName().equals(getString(R.string.car_detail_tag3))) {
                                    needRemove.add(carParam);
                                    e.onNext(carParam);
                                }
                                if (carParam.getCnName().equals("外观颜色")) {
                                    needRemove.add(carParam);
                                    e.onNext(carParam);
                                }
                                if (carParam.getCnName().equals("工信部综合油耗(L/100km)")) {
                                    needRemove.add(carParam);
                                    e.onNext(carParam);
                                }
                                if (carParam.getCnName().equals("厂商指导价(元)")) {
                                    needRemove.add(carParam);
                                    e.onNext(carParam);
                                }
                                if (carParam.getCnName().equals("车型名称")) {
                                    carModel.setName(carParam.getValue());
                                    needRemove.add(carParam);
                                    e.onNext(carParam);
                                }
                                if (carParam.getCnName().equals("品牌")) {
                                    needRemove.add(carParam);
                                    e.onNext(carParam);
                                }
                                if (carParam.getCnName().equals("品牌_id")) {
                                    needRemove.add(carParam);
                                    e.onNext(carParam);
                                }
                                if (carParam.getCnName().equals("车系")) {
                                    needRemove.add(carParam);
                                    e.onNext(carParam);

                                }
                                if (carParam.getCnName().equals("车系_id")) {
                                    needRemove.add(carParam);
                                    e.onNext(carParam);
                                }
                            }
                            CarParam carParam=new CarParam();
                            carParam.setParamType("finish");
                            e.onNext(carParam);
                            carDetailBaseResponse.getData().getCarEnList().remove(needRemove);
                        }).subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(carParam -> {
                                    if(carParam.getParamType().equals("finish")){

                                        carParamAdapter = new CarParamAdapter(getActivity(), carDetailBaseResponse.getData().getCarEnList());
                                        rvParam.setAdapter(carParamAdapter);

                                        mHolder.showLoadSuccess();
                                        return;
                                    }
                                    if (carParam.getCnName().equals(getString(R.string.car_detail_tag3))) {
                                        tvEngine.setText(carParam.getValue());
                                    } else if (carParam.getCnName().equals("外观颜色")) {
                                        String[] strings = carParam.getValue().split(";");
                                        carColorAdapter = new CarColorAdapter(getActivity(), Arrays.asList(strings));
                                        carColorAdapter.setOnClickListener(onItemClickListener);
                                        rvColor.setAdapter(carColorAdapter);
                                        tvColor.setText(getString(R.string.car_detail_color, strings.length));
                                    } else if (carParam.getCnName().equals("工信部综合油耗(L/100km)")) {
                                        tvGas.setText(carParam.getValue() + "(L/100km)");
                                    } else if (carParam.getCnName().equals("厂商指导价(元)")) {
                                        price2.setText(getString(R.string.car_detail_tag2, carParam.getValue()));
                                        price1.setText(carParam.getValue());
                                        carModel.setCarPrice(Double.valueOf(carParam.getValue().indexOf("万")));
                                    } else if (carParam.getCnName().equals("车型名称")) {
                                        tvCarModel.setText(carParam.getValue());
                                        carModel.setName(carParam.getValue());
                                    } else if (carParam.getCnName().equals("品牌")) {
                                        carBrand.setName(carParam.getValue());
                                    } else if (carParam.getCnName().equals("品牌_id")) {
                                        carSeries.setBrandId(Long.valueOf(carParam.getValue()));
                                        carBrand.setId(Long.valueOf(carParam.getValue()));
                                    } else if (carParam.getCnName().equals("车系")) {
                                        carSeries.setName(carParam.getValue());
                                    } else if (carParam.getCnName().equals("车系_id")) {
                                        carSeries.setId(Long.valueOf(carParam.getValue()));
                                    }

                                });



                    }
                });


    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    @Override
    public int layoutId() {
        return R.layout.fragment_car_detail;
    }

    @Override
    public boolean initView() {
        getDigger().inject(this);
        ViewGroup.LayoutParams layoutParams = toolbar.getLayoutParams();
        title.setText("车型信息");
        layoutParams.height = getStatusBarHeight(getContext()) + Tool.dip2px(getActivity(), 50);
        toolbar.setLayoutParams(layoutParams);
        toolbar.setPadding(0, getStatusBarHeight(getContext()), 0, 0);
        toolbar.setAlpha(0);
        int position = Integer.valueOf(CarDetailFragmentArgs.fromBundle(getArguments()).getPosition());
        carModel = carManagementViewModel.getCarModel().getValue().getData().get(position);
        Glide.with(getActivity())
                .load(R.mipmap.car_default)
                .into(ivLogo);
        if(carModel.isBeCollected()){
            ivCollect.setImageResource(R.mipmap.star_large_active);
        }else {
            ivCollect.setImageResource(R.mipmap.star_large);
        }
        ivHeight = Tool.dip2px(getActivity(), 250);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        rvColor.setLayoutManager(linearLayoutManager);
        rvColor.addItemDecoration(new HorizontalDecoration(getActivity(), 5, 0));
        rvParam.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvParam.addItemDecoration(new CustomDecoration(getActivity(), 0, 0, 15, 15));
        scrollView.setOnScrollChangeListener((BounceScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
            if (scrollY <= ivHeight * 2) {
                scrollView1.smoothScrollBy(0, (scrollY - oldScrollY) / 2);
            }
            if (scrollY < ivHeight) {
                ivBack1.setVisibility(View.GONE);
                float y = scrollY;
                float bottom = ivHeight;
                toolbar.setAlpha(y / bottom);
                if (y / bottom == 0) {
                    ivBack1.setVisibility(View.VISIBLE);
                }
            }


            if (scrollY >= ivHeight - toolbar.getHeight() + getStatusBarHeight(getActivity())) {


                if (scrollY > c.getTop() - toolbar.getHeight()) {
                    title.setText("基本参数");
                } else {
                    title.setText("车型信息");
                }
            }
        });

        rxTimer=new RxTimer();
        mHolder.showLoadingStatus(GlobalAdapter.LOADING_NOT_NEED_MARGIN);
        rxTimer.timer(400, number -> onLoadRetry());

        return false;
    }

    OnClickListener<String> onItemClickListener = new OnClickListener<String>() {
        @Override
        public void onItemClick(String s) {
            carColorAdapter.smoothMoveToPosition(rvColor, carColorAdapter.getCurrentClickPosition());
        }
    };

    @OnClick({R.id.iv_back, R.id.iv_back1})
    public void backClick() {
        NavHostFragment.findNavController(this).navigateUp();
    }

    @Override
    public void onDestroyView() {
        if(mDisposable!=null){
            mDisposable.dispose();
        }
        super.onDestroyView();
    }

    @OnClick(R.id.btn_booking)
    public void booking() {
        carBrandViewModel.getSelectedCarSeries().setValue(carSeries);
        carBrandViewModel.getSelectedCarBrand().setValue(carBrand);
        carBrandViewModel.getSelectedCarModel().setValue(carModel);
        go(null, R.id.action_carDetailFragment_to_addOrderFragment, null);
    }
    @OnClick(R.id.ll_collect)
    public void collect(){
        if(!carModel.isBeCollected()){
            carManagementViewModel.collectCarModel(carModel.getId())
                    .observe(this, new Observer<BaseResponse<CarModel>>() {
                        @Override
                        public void onChanged(BaseResponse<CarModel> carModelBaseResponse) {
                            carManagementViewModel.getCollectCarModel().removeObserver(this);
                            if(carModelBaseResponse.isSuccess()){
                                carModel.setBeCollected(true);
                                ivCollect.animate().scaleX(1.2f).scaleY(1.2f).setDuration(300).setListener(new AnimatorListenerAdapter() {
                                    @Override
                                    public void onAnimationEnd(Animator animation) {
                                        ivCollect.setScaleX(1);
                                        ivCollect.setScaleY(1);
                                    }
                                    @Override
                                    public void onAnimationStart(Animator animation) {
                                        ivCollect.setImageResource(R.mipmap.star_large_active);
                                    }
                                }).start();
                            }else {
                                showToast(carModelBaseResponse.getMsg());
                            }
                        }
                    });
        }else {
            ArrayList<CarModel> list=new ArrayList<>();
            list.add(carModel);
            carManagementViewModel.batchDelCarState(list)
                    .observe(this, new Observer<BaseResponse<Object>>() {
                        @Override
                        public void onChanged(BaseResponse<Object> objectBaseResponse) {
                            carManagementViewModel.getBatchDelCarState().removeObserver(this);
                            if(objectBaseResponse.isSuccess()){
                                carModel.setBeCollected(false);
                                ivCollect.setImageResource(R.mipmap.star_large);
                            }else {
                                showToast(objectBaseResponse.getMsg());
                            }
                        }
                    });
        }
    }
    @OnClick(R.id.ll_pk)
    public void pk(){
        carManagementViewModel.getCurrentNeedCompareCar().setValue(carModel);
        go(null,R.id.action_carDetailFragment_to_carPkFragment,null);
    }
}
